package dome2;

public class BinaryTree {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static int postIndex = 0;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(inorder == null && postorder == null) return null;
        postIndex = postorder.length - 1;
        return buildTreeChilk(inorder,postorder,0,inorder.length-1);
    }

    public TreeNode buildTreeChilk(int[] inorder, int[] postorder, int inbegin, int inend) {
        TreeNode root = new TreeNode(postorder[postIndex]);
        int rootIndex = find(inorder,inbegin,inend,postorder[postIndex]);
        postIndex--;
        root.left = buildTreeChilk(inorder,postorder,inbegin,rootIndex-1);
        root.right = buildTreeChilk(inorder,postorder,rootIndex+1,inend);
        return root;
    }

    private int find(int[] inorder,int inbegin,int inend, int key) {
        for (int i = inbegin; i <= inend; i++) {
            if(inorder[i] == key) return i;
        }
        return -1;
    }

//    public int postIndex = 0;
//
//    public TreeNode buildTree(int[] inorder, int[] postorder) {
//        postIndex = postorder.length - 1;
//        return buildTreeChilde(inorder, postorder, 0, inorder.length - 1);
//    }
//
//    public TreeNode buildTreeChilde(int[] inorder, int[] postorder, int inbegin, int inend) {
//        if (inbegin > inend) return null;
//        TreeNode root = new TreeNode(postorder[postIndex]);
//        int rootIndex = findVal(inorder, inbegin, inend, postorder[postIndex]);
//        postIndex--;
//        root.right = buildTreeChilde(inorder, postorder, rootIndex + 1, inend);
//        root.left = buildTreeChilde(inorder, postorder, inbegin, rootIndex - 1);
//        return root;
//    }
//
//    private int findVal(int[] inorder, int inbegin, int inend, int key) {
//        for (int i = inbegin; i <= inend; i++) {
//            if (inorder[i] == key) {
//                return i;
//            }
//        }
//        return -1;
//    }
}















































